<template>
	<view class="page-common page-versatile-show-operator photo-operator">
		<view v-if="processedShuiYinUrl" class="fixed-top-tab">
			<switch-tab  :current="currentTab" :list="topTabs"
				@change="onTopTabChange"></switch-tab>
		</view>
		
		<view class="top-container flex-center">
			<template v-if="photoUrl">
				<!-- 单张 -->
				<view class="photo-wrap">
					<image class="photo-image" :style="photoImageStyle" :src="photoUrl" mode="aspectFit"></image>
				</view>

				<!-- <view v-if="currentTab === 0" class="reupload-button custom-button white-btn-gray-text"
					@tap="onChoosePhoto">
					<u-button type="primary" shape="circle" text="重新上传"></u-button>
				</view> -->

			</template>
			<template v-else>
				<view class="upload-box" @tap="onChoosePhoto">
					<text class="add-icon">+</text>
					<view class="add-text">点击上传你的照片</view>
				</view>
			</template>
		</view>

		<view class="field-container" v-if="currentTab === 0">
			<view class="flex-column-gap-16">
				<view class="plr-16 pb-16 flex-column-gap-10">
					<view class="flex-between-center ">
						<text class="normal-title-bold-16">{{prdName}}</text>
						<text class="normal-title-bold-20 blue-text">{{dataInfo.discountGoldenBean}}<text
								class="font-12">金豆</text></text>
					</view>
					<view class="blue-text">金豆余额：{{dataInfo.restAmount}}<text class="desc-14">（10金豆=1元）</text></view>
					<view class="split-line"></view>
					<view class="flex-column-gap-5" @click="toPage('/pages/my/voucherCenter')">
						<view class="normal-title">服务说明</view>
						<view class="desc-14">
							<view>体验本服务需消耗金豆，如金豆不足可 <text class="blue-text underline font-17">点击充值</text></view>
							<view>生成效果图后金豆将自动扣除，消耗金豆无法退回</view>
						</view>
					</view>
				</view>

			</view>
			<view class="custom-button full-button" @tap="onGenerate">
				<u-button type="primary" shape="circle" text="生成效果" :disabled="!couldSubmit"></u-button>
			</view>
		</view>
		<view class="field-container" v-else>
			<view class="normal-title-16 text-center">
				<text>效果生成成功！</text>
			</view>
			<view class="mt-7 text-center desc-14">金豆余额：{{dataInfo.restAmount}}金豆</view>
			<view class="switch-box mt-20">
				<choose-box :list="switchList" :current="currentValue" @change="onChange" />
			</view>
			<view class="custom-button full-button mt-20" @tap="onSavePhoto">
				<u-button type="primary" shape="circle" text="保存照片"></u-button>
			</view>
		</view>
		<custom-popup v-model:show="showPopup.showConfirm" title="确认是否生成效果？" content="确认生成后金豆将自动扣除"
			@confirm="onConfirm">
		</custom-popup>
		
	</view>
</template>
<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		computed,
	} from "vue";

	import {
		checkUploadImage,
		getImgScaleStyle,
		getUserInfo,
	} from '@/common/js/method';
	import customPopup from '@/components/custom-popup/custom-popup.vue';
	import chooseBox from '@/components/choose-box/index.vue';
	import switchTab from '@/components/switch-tab/index.vue';

	import {
		versatileShowMap,
	} from '@/common/js/data';
	const busiType = ref('black-white-coloring');
	const userImage = ref(''); //用户上传的图片
	const imageInfo = ref({});
	const processedShuiYinUrl = ref(''); //处理后带水印
	const processedImgUrl = ref(''); //处理后
	const processedImgUrls = ref({}); //缓存所有处理后的图片，下次不需要发接口重新处理
	const dataInfo = reactive({
		discountGoldenBean: '', //金豆价格
		restAmount: '', //金豆余额
	});
	const showPopup = reactive({
		showConfirm: false,
		showSuccess: false,
	})

	// 可以提交的条件（余额不为零且大于等于标价）
	const couldSubmit = computed(() => {
		const isHasAmount = +dataInfo.restAmount && +dataInfo.restAmount >= +dataInfo.discountGoldenBean;
		return userImage.value && isHasAmount;
	});

	//顶部tab相关-start
	const topTabs = ['原画', '结果图'];
	const currentTab = ref(0);

	// 切换显示的图片
	const photoUrl = computed(() => {
		return [userImage.value, processedShuiYinUrl.value][currentTab.value];
	});
	const onTopTabChange = (index) => {
		currentTab.value = index;
	}
	//顶部tab相关-end

	// 缩放图片
	const photoImageStyle = computed(() => {
		return getImgScaleStyle(imageInfo.value.width, imageInfo.value.height, 300)
	});

	// 名称
	const prdName = computed(() => {
		return versatileShowMap[busiType.value].name;
	})

	// 切换列表
	const switchList = computed(() => versatileShowMap[busiType.value].switchList);
	// 默认选中的效果
	const currentValue = ref('');

	const getRestAmount = async () => {
		await getUserInfo();
		const {
			goldenBean
		} = uni.getStorageSync('userInfo');
		dataInfo.restAmount = goldenBean;
	}

	const onGenerate = () => {
		if (!couldSubmit.value) return;
		showPopup.showConfirm = true;
	}
	const onConfirm = async () => {
		await processed();
		await getRestAmount()
		uni.hideLoading();
		currentTab.value = 1;
		showPopup.showSuccess = true;
	}


	const addCache = (obj) => {
		processedImgUrls.value[currentValue.value] = obj;
	};

	const getCache = () => {
		return processedImgUrls.value[currentValue.value];
	};
	const clearCache = () => {
		processedImgUrls.value = {};
	};

	const onChoosePhoto = async () => {
		const res = await checkUploadImage({
			limit: {
				width: 4000,
				height: 4000,
				fileSize: 3072, //3M
				types: ['JPG', 'JPEG', 'BMP', 'PNG'],
			}
		});
		userImage.value = res.uploadedSrc;
		imageInfo.value = {
			width: res.width,
			height: res.height,
			type: res.type,
			fileSize: res.fileSize,
		};
		clearCache();
	}

	// 图像格式更换处理接口
	const processed = async (isChange) => {
		if (!userImage.value) {
			return;
		}
		uni.showLoading({
			title: '处理中'
		});

		const payload = {
			payAmount: isChange ? 0 : dataInfo.discountGoldenBean,
			imageUrl: userImage.value,
			currentValue: currentValue.value,
		}

		let data = await versatileShowMap[busiType.value].api(payload);

		processedShuiYinUrl.value = data.shuiyinUrl;
		processedImgUrl.value = data.imageUrl;

		// 如果有切换列表（素描照和漫画照）,需要缓存
		if (switchList.value && !getCache()) {
			addCache(data);
		}

	}

	const onChange = (item) => {
		currentValue.value = item.value;
		let data = getCache();
		if (data) {
			processedShuiYinUrl.value = data.shuiyinUrl;
			processedImgUrl.value = data.imageUrl;
			return;
		}
		processed(true);
	}

	const onSavePhoto = () => {
		const data = {
			width: imageInfo.value.width,
			height: imageInfo.value.height,
			imgType: imageInfo.value.type,
			fileSize: imageInfo.value.fileSize,
			photoStyle: currentValue.value,
			// shuiyinUrl: encodeURIComponent(userImage.value), //处理后的水印照片
			// imageUrl: encodeURIComponent(userImage.value), //处理后的无水印照片
			shuiyinUrl: encodeURIComponent(processedShuiYinUrl.value), //处理后的水印照片
			imageUrl: encodeURIComponent(processedImgUrl.value), //处理后的无水印照片
		};
		// let strParams = uni.$getQueryStr({
		// 	type: busiType.value,
		// 	data: JSON.stringify(data)
		// });
		// console.log('strParams', strParams)
		uni.navigateTo({
			url: `/pages/versatile-show/photo-save?type=${busiType.value}&data=${JSON.stringify(data)}`
		})

	}
	const toPage = (path) => {
		uni.navigateTo({
			url: path,
		})
	}

	onLoad((params) => {
		if (params.type) {
			busiType.value = params.type;
		}
		uni.setNavigationBarTitle({
			title: prdName.value,
		})
		if (params.data) {
			const data = JSON.parse(params.data);
			dataInfo.discountGoldenBean = data.discountGoldenBean;
			imageInfo.value = {
				width: data.width,
				height: data.height,
				type: data.imageType,
				fileSize: data.fileSize,
			};
			userImage.value = decodeURIComponent(data.imageUrl);
		}
		// 有切换列表时，设置默认值
		if (switchList.value) {
			currentValue.value = versatileShowMap[busiType.value].defaultValue
		};

		getRestAmount();
	})
</script>

<style lang="scss" scoped>
	@import "@/common/style/photo-operator.scss";

	.page-black-white-coloring {

		// .top-container {
		// 	height: calc(100vh - 340rpx);
		// }

		// .field-container {
		// 	padding-top: 32rpx;
		// 	height: 340rpx;
		// }
	}
</style>